home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / share / python / pyversions.py < prev   
Text File  |  2009-10-30  |  14KB  |  376 lines

  1. #! /usr/bin/python
  2.  
  3. import os, re, sys
  4. try:
  5.     SetType = set
  6. except NameError:
  7.     import sets
  8.     SetType = sets.Set
  9.     set = sets.Set
  10.  
  11. _defaults = None
  12. def read_default(name=None):
  13.     global _defaults
  14.     from ConfigParser import SafeConfigParser, NoOptionError
  15.     if not _defaults:
  16.         if os.path.exists('/usr/share/python/debian_defaults'):
  17.             config = SafeConfigParser()
  18.             config.readfp(file('/usr/share/python/debian_defaults'))
  19.             _defaults = config
  20.     if _defaults and name:
  21.         try:
  22.             value = _defaults.get('DEFAULT', name)
  23.         except NoOptionError:
  24.             raise ValueError
  25.         return value
  26.     return None
  27.  
  28. def parse_versions(vstring, add_exact=False):
  29.     import operator
  30.     operators = { None: operator.eq, '=': operator.eq,
  31.                   '>=': operator.ge, '<=': operator.le,
  32.                   '<<': operator.lt
  33.                   }
  34.     vinfo = {}
  35.     exact_versions = set([])
  36.     version_range = set(supported_versions(version_only=True)
  37.                         + old_versions(version_only=True))
  38.     relop_seen = False
  39.     for field in vstring.split(','):
  40.         field = field.strip()
  41.         if field == 'all':
  42.             vinfo['all'] = 'all'
  43.             continue
  44.         if field in ('current', 'current_ext'):
  45.             vinfo['current'] = field
  46.             continue
  47.         vinfo.setdefault('versions', set())
  48.         ve = re.compile('(>=|<=|<<|=)? *(\d\.\d)$')
  49.         m = ve.match(field)
  50.         try:
  51.             op, v = m.group(1), m.group(2)
  52.             if op in (None, '='):
  53.                 exact_versions.add(v)
  54.             else:
  55.                 relop_seen = True
  56.                 filtop = operators[op]
  57.                 version_range = [av for av in version_range if filtop(av ,v)]
  58.         except Exception:
  59.             raise ValueError, 'error parsing Python-Version attribute'
  60.     if add_exact:
  61.         if exact_versions:
  62.             vinfo['vexact'] = exact_versions
  63.         if 'versions' in vinfo:
  64.             if relop_seen:
  65.                 vinfo['versions'] = set(version_range)
  66.             else:
  67.                 del vinfo['versions']
  68.     else:
  69.         if 'versions' in vinfo:
  70.             vinfo['versions'] = exact_versions
  71.             if relop_seen:
  72.                 vinfo['versions'] = exact_versions.union(version_range)
  73.     return vinfo
  74.  
  75. _old_versions = None
  76. def old_versions(version_only=False):
  77.     global _old_versions
  78.     if not _old_versions:
  79.         try:
  80.             value = read_default('old-versions')
  81.             _old_versions = [s.strip() for s in value.split(',')]
  82.         except ValueError:
  83.             _old_versions = []
  84.     if version_only:
  85.         return [v[6:] for v in _old_versions]
  86.     else:
  87.         return _old_versions
  88.  
  89. _unsupported_versions = None
  90. def unsupported_versions(version_only=False):
  91.     global _unsupported_versions
  92.     if not _unsupported_versions:
  93.         try:
  94.             value = read_default('unsupported-versions')
  95.             _unsupported_versions = [s.strip() for s in value.split(',')]
  96.         except ValueError:
  97.             _unsupported_versions = []
  98.     if version_only:
  99.         return [v[6:] for v in _unsupported_versions]
  100.     else:
  101.         return _unsupported_versions
  102.  
  103. _supported_versions = None
  104. def supported_versions(version_only=False):
  105.     global _supported_versions
  106.     if not _supported_versions:
  107.         try:
  108.             value = read_default('supported-versions')
  109.             _supported_versions = [s.strip() for s in value.split(',')]
  110.         except ValueError:
  111.             cmd = ['/usr/bin/apt-cache', '--no-all-versions',
  112.                    'show', 'python-all']
  113.             try:
  114.                 import subprocess
  115.                 p = subprocess.Popen(cmd, bufsize=1,
  116.                                      shell=False, stdout=subprocess.PIPE)
  117.                 fd = p.stdout
  118.             except ImportError:
  119.                 fd = os.popen(' '.join(cmd))
  120.             depends = None
  121.             for line in fd:
  122.                 if line.startswith('Depends:'):
  123.                     depends = line.split(':', 1)[1].strip().split(',')
  124.             fd.close()
  125.             if depends:
  126.                 depends = [re.sub(r'\s*(\S+)[ (]?.*', r'\1', s) for s in depends]
  127.                 _supported_versions = depends
  128.             if not _supported_versions:
  129.                 # last resort: python-minimal not installed, apt-cache
  130.                 # not available, hard code the value, #394084
  131.                 _supported_versions = ['python2.4', 'python2.5']
  132.     if version_only:
  133.         return [v[6:] for v in _supported_versions]
  134.     else:
  135.         return _supported_versions
  136.  
  137. _default_version = None
  138. def default_version(version_only=False):
  139.     global _default_version
  140.     if not _default_version:
  141.         try:
  142.             _default_version = link = os.readlink('/usr/bin/python')
  143.         except OSError:
  144.             _default_version = None
  145.             try:
  146.                 cmd = ['/usr/bin/python', '-c', 'import sys; print sys.version[:3]']
  147.                 import subprocess
  148.                 p = subprocess.Popen(cmd, bufsize=1,
  149.                                      shell=False, stdout=subprocess.PIPE)
  150.                 fd = p.stdout
  151.             except ImportError:
  152.                 fd = os.popen("/usr/bin/python -c 'import sys; print sys.version[:3]'")
  153.             line = fd.readline().strip()
  154.             fd.close()
  155.             if re.match(r'\d\.\d$', line):
  156.                 _default_version = 'python' + line
  157.         # consistency check
  158.         try:
  159.             debian_default = read_default('default-version')
  160.         except ValueError:
  161.             debian_default = "python2.5"
  162.         if not _default_version in (debian_default, os.path.join('/usr/bin', debian_default)):
  163.             raise ValueError, "/usr/bin/python does not match the python default version. It must be reset to point to %s" % debian_default
  164.         _default_version = debian_default
  165.     if version_only:
  166.         return _default_version[6:]
  167.     else:
  168.         return _default_version
  169.  
  170. def requested_versions(vstring, version_only=False):
  171.     versions = None
  172.     vinfo = parse_versions(vstring, add_exact=True)
  173.     supported = supported_versions(version_only=True)
  174.     if len(vinfo) == 1:
  175.         if 'all' in vinfo:
  176.             versions = supported
  177.         elif 'current' in vinfo:
  178.             versions = [default_version(version_only=True)]
  179.         elif 'vexact' in vinfo:
  180.             versions = vinfo['vexact']
  181.         else:
  182.             versions = vinfo['versions'].intersection(supported)
  183.     elif 'all' in vinfo and 'current' in vinfo:
  184.         raise ValueError, "both `current' and `all' in version string"
  185.     elif 'all' in vinfo:
  186.         if 'versions' in vinfo:
  187.             versions = vinfo['versions'].intersection(supported)
  188.         else:
  189.             versions = set(supported)
  190.         if 'vexact' in vinfo:
  191.             versions.update(vinfo['vexact'])
  192.     elif 'current' in vinfo:
  193.         current = default_version(version_only=True)
  194.         if not current in vinfo['versions']:
  195.             raise ValueError, "`current' version not in supported versions"
  196.         versions = [current]
  197.     elif 'versions' in vinfo or 'vexact' in vinfo:
  198.         versions = set()
  199.         if 'versions' in vinfo:
  200.             versions = vinfo['versions'].intersection(supported)
  201.         if 'vexact' in vinfo:
  202.             versions.update(vinfo['vexact'])
  203.     else:
  204.         raise ValueError, 'error in version string'
  205.     if not versions:
  206.         raise PyCentralEmptyValueError, 'empty set of versions'
  207.     if version_only:
  208.         return versions
  209.     else:
  210.         return ['python%s' % v for v in versions]
  211.  
  212. def installed_versions(version_only=False):
  213.     import glob
  214.     supported = supported_versions()
  215.     versions = [os.path.basename(s)
  216.                 for s in glob.glob('/usr/bin/python[0-9].[0-9]')
  217.                 if os.path.basename(s) in supported]
  218.     versions.sort()
  219.     if version_only:
  220.         return [v[6:] for v in versions]
  221.     else:
  222.         return versions
  223.  
  224. class ControlFileValueError(ValueError):
  225.     pass
  226. class MissingVersionValueError(ValueError):
  227.     pass
  228.  
  229. def extract_pyversion_attribute(fn, pkg):
  230.     """read the debian/control file, extract the XS-Python-Version
  231.     field; check that XB-Python-Version exists for the package."""
  232.  
  233.     version = None
  234.     sversion = None
  235.     section = None
  236.     for line in file(fn):
  237.         line = line.strip()
  238.         if line == '':
  239.             if section == None:
  240.                 continue
  241.             if pkg == 'Source':
  242.                 break
  243.             section = None
  244.         elif line.startswith('Source:'):
  245.             section = 'Source'
  246.         elif line.startswith('Package: ' + pkg):
  247.             section = pkg
  248.         elif line.startswith('XS-Python-Version:'):
  249.             if section != 'Source':
  250.                 raise ValueError, \
  251.                       'attribute XS-Python-Version not in Source section'
  252.             sversion = line.split(':', 1)[1].strip()
  253.         elif line.startswith('XB-Python-Version:'):
  254.             if section == pkg:
  255.                 version = line.split(':', 1)[1].strip()
  256.     if section == None:
  257.         raise ControlFileValueError, 'not a control file'
  258.     if pkg == 'Source':
  259.         if sversion == None:
  260.             raise MissingVersionValueError, \
  261.                   'missing XS-Python-Version in control file'
  262.         return sversion
  263.     if version == None:
  264.         raise MissingVersionValueError, \
  265.               'missing XB-Python-Version for package `%s' % pkg
  266.     return version
  267.  
  268. # compatibility functions to parse debian/pyversions
  269.  
  270. def version_cmp(ver1,ver2):
  271.     v1=[int(i) for i in ver1.split('.')]
  272.     v2=[int(i) for i in ver2.split('.')]
  273.     return cmp(v1,v2)
  274.  
  275. def requested_versions_bis(vstring, version_only=False):
  276.     versions = []
  277.     py_supported_short = supported_versions(version_only=True)
  278.     for item in vstring.split(','):
  279.         v=item.split('-')
  280.         if len(v)>1:
  281.             if not v[0]:
  282.                 v[0] = py_supported_short[0]
  283.             if not v[1]:
  284.                 v[1] = py_supported_short[-1]
  285.             for ver in py_supported_short:
  286.                 try:
  287.                     if version_cmp(ver,v[0]) >= 0 \
  288.                            and version_cmp(ver,v[1]) <= 0:
  289.                         versions.append(ver)
  290.                 except ValueError:
  291.                     pass
  292.         else:
  293.             if v[0] in py_supported_short:
  294.                 versions.append(v[0])
  295.     versions.sort(version_cmp)
  296.     if not versions:
  297.         raise ValueError, 'empty set of versions'
  298.     if not version_only:
  299.         versions=['python'+i for i in versions]
  300.     return versions
  301.  
  302. def extract_pyversion_attribute_bis(fn):
  303.     vstring = file(fn).readline().rstrip('\n')
  304.     return vstring
  305.  
  306. def main():
  307.     from optparse import OptionParser
  308.     usage = '[-v] [-h] [-d|--default] [-s|--supported] [-i|--installed] [-r|--requested <version string>|<control file>]'
  309.     parser = OptionParser(usage=usage)
  310.     parser.add_option('-d', '--default',
  311.                       help='print the default python version',
  312.                       action='store_true', dest='default')
  313.     parser.add_option('-s', '--supported',
  314.                       help='print the supported python versions',
  315.                       action='store_true', dest='supported')
  316.     parser.add_option('-r', '--requested',
  317.                       help='print the python versions requested by a build; the argument is either the name of a control file or the value of the XS-Python-Version attribute',
  318.                       action='store_true', dest='requested')
  319.     parser.add_option('-i', '--installed',
  320.                       help='print the installed supported python versions',
  321.                       action='store_true', dest='installed')
  322.     parser.add_option('-v', '--version',
  323.                       help='print just the version number(s)',
  324.                       default=False, action='store_true', dest='version_only')
  325.     opts, args = parser.parse_args()
  326.     program = os.path.basename(sys.argv[0])
  327.  
  328.     if opts.default and len(args) == 0:
  329.         try:
  330.             print default_version(opts.version_only)
  331.         except ValueError, msg:
  332.             print "%s:" % program, msg
  333.             sys.exit(1)
  334.     elif opts.supported and len(args) == 0:
  335.         print ' '.join(supported_versions(opts.version_only))
  336.     elif opts.installed and len(args) == 0:
  337.         print ' '.join(installed_versions(opts.version_only))
  338.     elif opts.requested and len(args) <= 1:
  339.         if len(args) == 0:
  340.             versions = 'debian/control'
  341.         else:
  342.             versions = args[0]
  343.         try:
  344.             if os.path.isfile(versions):
  345.                 fn = versions
  346.                 try:
  347.                     vstring = extract_pyversion_attribute(fn, 'Source')
  348.                     vs = requested_versions(vstring, opts.version_only)
  349.                 except ControlFileValueError:
  350.                     sys.stderr.write("%s: not a control file: %s, " \
  351.                                      % (program, fn))
  352.                     sys.exit(1)
  353.                 except MissingVersionValueError:
  354.                     fn = os.path.join(os.path.dirname(fn), 'pyversions')
  355.                     sys.stderr.write("%s: missing XS-Python-Version in control file, fall back to %s\n" \
  356.                                      % (program, fn))
  357.                     try:
  358.                         vstring = extract_pyversion_attribute_bis(fn)
  359.                         vs = requested_versions_bis(vstring, opts.version_only)
  360.                     except IOError:
  361.                         sys.stderr.write("%s: missing debian/pyversions file, fall back to supported versions\n" \
  362.                                          % program)
  363.                         vs = supported_versions(opts.version_only)
  364.             else:
  365.                 vs = requested_versions(versions, opts.version_only)
  366.             print ' '.join(vs)
  367.         except ValueError, msg:
  368.             sys.stderr.write("%s: %s\n" % (program, msg))
  369.             sys.exit(1)
  370.     else:
  371.         sys.stderr.write("usage: %s %s\n" % (program, usage))
  372.         sys.exit(1)
  373.  
  374. if __name__ == '__main__':
  375.     main()
  376.